
import path from 'path'
import fs from 'fs-extra'
import inquirer from 'inquirer'
import ini from 'ini'
import _ from 'lodash'
import ora from 'ora'
import { GMC_CONF, GMC_PATH, GMC_CONFILE, getProjectList, getInterfaces, getInterfaceList } from './base'

export default () => {
  let projectList = getProjectList()
  if (projectList.length === 0) {
    console.log(`\n   还没有项目建立，先去创建一个 !\n`)
    return
  }
  return inquirerMainOptions(projectList)
}

// 主选项栏
const inquirerMainOptions = (projectList) => {
  let project = null
  return inquirer.prompt([
    {
      type: 'list',
      name: 'project',
      message: '选择一个项目 ?',
      choices: projectList
    }
  ])
  .then( ret => {
    project = ret.project.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
    return inquirer.prompt([
      {
        type: 'list',
        name: 'option',
        message: 'API接口配置选项 ?',
        choices: [
          {
            key: '0',
            name: '1) 添加API接口',
            value: 'create'
          },
          {
            key: '1',
            name: '2) 修改API接口',
            value: 'edit'
          },
          {
            key: '2',
            name: '3) 删除API接口',
            value: 'remove'
          },
          {
            key: '3',
            name: '4) 返回上一级',
            value: 'back'
          },
        ]
      }
    ])
  })
  .then( ret => {
    switch (ret.option) {
      case 'create': {
        return addInterface(project)
      }
      case 'edit': {
        return editInterface(project)
      }
      case 'remove': {
        return removeInterface(project)
      }
      case 'back': {
        return inquirerMainOptions(projectList)
      }
      default:
        break
    }
  })
}

// 添加一个接口
const addInterface = (project) => {
  let options = null
  let projectConf = GMC_CONF[project]
  let apiConfigDir = path.resolve(GMC_PATH, projectConf.path, 'api')
  !fs.existsSync(apiConfigDir) && fs.mkdirpSync(apiConfigDir)
  let interfaces = getInterfaces(project)
  return inquirer.prompt([
    {
      type: 'input',
      name: 'tag',
      message: '接口标志 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '接口标志不能为空 !'
        }
        if (_.has(interfaces, value)) {
          return '接口标志已存在 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'code',
      message: '接口编号 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '接口编号不能为空 !'
        }
        if (!/(\d+){2,6}/.test(value)) {
          return '接口编号格式错误 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'msg',
      message: '接口描述 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '接口描述不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'req',
      message: '请求模块名称 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '请求模块名称不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'res',
      message: '接收模块名称 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '接收模块名称不能为空 !'
        }
        return true
      }
    }
  ])
  .then( ret => {
    options = { ...options, ...ret }
    console.log(`  开始添加参数 ...`)
    return inquirerParams()
  })
  .then( ret => {
    options = { ...options, params: ret }
    console.log(`  开始添加视图模块 ...`)
    return inquirer.prompt([
      {
        type: 'input',
        name: 'splitter',
        message: '分隔符 ?'
      }
    ])
  })
  .then( ret => {
    options = { ...options, display: ret }
    return inquirerDisplayHeader()
  })
  .then( ret => {
    options = { 
      ...options, 
      display: {
        ...options.display,
        header: ret
      }
    }
    return inquirer.prompt([
      {
        type: 'input',
        name: 'group',
        message: '视图表格分组 ?'
      }
    ])
  })
  .then( ret => {
    let group = ret.group.split(/\,/)
    options = { 
      ...options, 
      display: {
        ...options.display,
        ...group.length > 1 ? { group } : null
      }
    }
    let apiConfig = {
      [options.tag]: _.omit(options, ['tag'])
    }
    console.log('')
    let spinner = ora(`    Create API Interface ...`).start()
    let apiConfigData = ini.stringify(apiConfig, { whitespace: true })
    fs.writeFileSync(path.resolve(apiConfigDir, `${options.code}.ini`), apiConfigData, 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Create API Interface !\n')
    }, 500)
  })
}

// 修改一个接口
const editInterface = (project) => {
  let options = null
  let interfaceTag = null
  let interfaceInfo = null
  let projectConf = GMC_CONF[project]
  let apiConfigDir = path.resolve(GMC_PATH, projectConf.path, 'api')
  let interfaces = getInterfaces(project)
  let interfaceList = getInterfaceList(project)
  if (interfaceList.length === 0) {
    console.log(`\n   还没有API接口配置 !\n`)
    return 
  }
  return inquirer.prompt([
    {
      type: 'list',
      name: 'tag',
      message: '选择一个API接口 ?',
      choices: interfaceList
    }
  ])
  .then( ret => {
    interfaceTag = ret.tag.replace(/(\[)([a-zA-Z\_]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
    interfaceInfo = interfaces[interfaceTag]
    options = interfaceInfo
    return inquirer.prompt([
      {
        type: 'input',
        name: 'msg',
        message: '接口描述 ?',
        default: interfaceInfo['msg'],
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '接口描述不能为空 !'
          }
          return true
        }
      },
      {
        type: 'input',
        name: 'req',
        message: '请求模块名称 ?',
        default: interfaceInfo['req'],
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '请求模块名称不能为空 !'
          }
          return true
        }
      },
      {
        type: 'input',
        name: 'res',
        message: '接收模块名称 ?',
        default: interfaceInfo['res'],
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '接收模块名称不能为空 !'
          }
          return true
        }
      }
    ])
  })
  .then( ret => {
    options = { ...options, ...ret }
    return inquirerParamsOption(interfaceInfo['params'])
    
  })
  .then( ret => {
    options = { ...options, params: ret }
    return inquirerEditDisplay(interfaceInfo['display'])
  })
  .then( ret => {
    options = { ...options, display: ret }
    let apiConfig = {
      [interfaceTag]: options
    }
    console.log('')
    let spinner = ora(`    Edit API Interface ...`).start()
    let apiConfigData = ini.stringify(apiConfig, { whitespace: true })
    fs.writeFileSync(path.resolve(apiConfigDir, `${options.code}.ini`), apiConfigData, 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete EDit API Interface !\n')
    }, 500)
  })
}

// 删除一个或多个接口
const removeInterface = (project) => {
  let projectConf = GMC_CONF[project]
  let apiConfigDir = path.resolve(GMC_PATH, projectConf.path, 'api')
  let interfaceList = getInterfaceList(project)
  return inquirer.prompt([
    {
      type: 'checkbox',
      name: 'interface',
      message: '选择要删除的接口 ?',
      choices: interfaceList
    }
  ])
  .then( ret => {
    if (ret.interface.length === 0) {
      console.log(`\n   没有选择任何接口 !\n`)
      return
    }
    let interfaces = getInterfaces(project)
    console.log('')
    let spinner = ora(`    Remove API Interface ...`).start()
    for (let item of ret.interface) {
      let tag = item.replace(/(\[)([a-zA-Z\_]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
      let info = interfaces[tag] || null
      if (info) {
        let filePath = path.resolve(apiConfigDir, `${info.code}.ini`)
        fs.removeSync(filePath)
      }
    }
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Remove API Interface !\n')
    }, 500)
  })
}

// 添加接口参数
const inquirerParams = (params = null) => {
  return inquirer.prompt([
    {
      type: 'input',
      name: 'name',
      message: '参数名称 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '参数名称不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'type',
      message: '参数类型 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '参数类型不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'message',
      message: '参数描述 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '参数描述不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'pattern',
      message: '验证格式 ?'
    },
    {
      type: 'input',
      name: 'format',
      message: '格式化 ?'
    },
    {
      type: 'list',
      name: 'required',
      message: '是否必填项 ?',
      choices: [ 'true', 'false' ]
    }
  ])
  .then( ret => {
    let opts = _.pick(ret, ['type', 'message', 'required'])
    if (ret.pattern.length > 0) opts.pattern = ret.pattern
    if (ret.format.length > 0) opts.format = ret.format
    params = {
      ...params,
      [ret.name]: opts
    }
    return inquirer.prompt([
      {
        type: 'confirm',
        name: 'isNext',
        message: '继续添加参数 ?',
        default: true
      }
    ])
  })
  .then( ret => {
    if(ret.isNext) {
      return inquirerParams(params)
    }
    return params
  })
}

// 创建试图头部
const inquirerDisplayHeader = (header = []) => {
  return inquirer.prompt([
    {
      type: 'input',
      name: 'header',
      message: '表格头部格式 ?'
    },
    {
      type: 'confirm',
      name: 'isNext',
      message: '继续添加表格头部 ?',
      default: true
    }
  ])
  .then( ret => {
    header.push(ret.header)
    if(ret.isNext) {
      return inquirerDisplayHeader(header)
    }
    else {
      return header
    }
  })
}

// 接口参数操作选项
const inquirerParamsOption = (params = null) => {
  let tag = null
  let index = 0
  let tagOpts = []
  for (let item of _.keys(params)) {
    tagOpts.push({
      key: index,
      name: `${index+1}) 参数 -> ${item}`,
      value: item
    })
    index++
  }
  return inquirer.prompt([
    {
      type: 'list',
      name: 'tag',
      message: '参数选项 ?',
      choices: _.concat(tagOpts, {
        key: index,
        name: `${index+1}) 添加新参数`,
        value: '::create'
      }, {
        key: index + 1,
        name: `${index+2}) 跳过此项选择`,
        value: '::next'
      })
    }
  ])
  .then( ret => {
    tag = ret.tag
    if ( /(\:){2}(create|next)/.test(ret.tag)) {
      return { option: ret.tag }
    }
    return inquirer.prompt([
      {
        type: 'list',
        name: 'option',
        message: '操作选项 ?',
        choices: [
          {
            key: 0,
            name: '1) 修改',
            value: '::edit'
          },
          {
            key: 1,
            name: '2) 移除',
            value: '::remove'
          },
          {
            key: 2,
            name: '3) 返回',
            value: '::back'
          }
        ]
      }
    ])
  })
  .then( ret => {
    if (ret.option === '::edit') {
      return inquirerEditParam(params, tag)
    }
    if (ret.option === '::remove') {
      _.unset(params, tag)
      return params
    }
    if (ret.option === '::back') {
      return params
    }
    if (ret.option === '::create') {
      return inquirerParams(params)
    }
    return { next: true }
  })
  .then( ret => {
    if (ret.next) {
      return params
    }
    return inquirerParamsOption(ret)
  })
}

// 修改接口参数
const inquirerEditParam = (params, tag) => {
  let info = params[tag]
  return inquirer.prompt([
    {
      type: 'input',
      name: 'type',
      message: '参数类型 ?',
      default: info['type'],
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '参数类型不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'message',
      message: '参数描述 ?',
      default: info['message'],
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '参数描述不能为空 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'pattern',
      message: '验证格式 ?',
      default: info['pattern']
    },
    {
      type: 'input',
      name: 'format',
      message: '格式化 ?',
      default: info['format']
    },
    {
      type: 'list',
      name: 'required',
      message: '是否必填项 ?',
      choices: [ 'true', 'false' ],
      default: info['required']
    }
  ])
  .then( ret => {
    return {
      ...params,
      [tag]: ret
    }
  })
}

// 修改视图模块
const inquirerEditDisplay = (display) => {
  console.log(`  开始修改视图模块 ...`)
  let options = display
  return inquirer.prompt([
    {
      type: 'input',
      name: 'splitter',
      message: '分隔符 ?',
      default: display['splitter']
    }
  ])
  .then( ret => {
    options = { ...options, ...ret }

    return inquirer.prompt([
      {
        type: 'editor',
        name: 'header',
        message: '表格头部格式 ?',
        default: _.join(display['header'], '\n')
      },
      {
        type: 'input',
        name: 'group',
        message: '视图表格分组 ?',
        default: _.has(display, 'group') ? _.join(display['group'], ',') : ''
      }
    ])
  })
  .then( ret => {
    let group = ret.group.split(/\,/)
    options = { 
      ...options, 
      header: ret.header.split(/\n/),
      ...group.length > 1 ? { group } : null
    }
    return options
  })
}